﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Descriptions_DomainModel.Model;
using Eco.Handles;
using Eco.Services;

namespace DomainModelEditor
{
    public partial class FunctionEditForm : Form
    {
        private IUndoService undo;
        private bool result = false;

        private Function Function
        {
            get
            {
                return FunctionVH.Element.AsObject as Function;
            }
        }

        private EcoSpace EcoSpace
        {
            get
            {
                return FunctionVH.EcoSpace;
            }
        }

        public FunctionEditForm(EcoSpace ecoSpace, Function function)
        {
            if (ecoSpace == null)
                throw new NullReferenceException("EcoSpace cannot be null!");
            if (function == null)
                throw new NullReferenceException("Function cannot be null!");

            InitializeComponent();

            undo = ecoSpace.GetEcoService<IUndoService>();

            if (undo == null)
                throw new NullReferenceException("UndoService must be registered in EcoSpace for MethodEditForm to work!");

            FunctionVH.EcoSpace = ecoSpace;

            FunctionVH.SetElementValue<Function>(function);
        }

        #region Parameters

        private void AddParamButton_Click(object sender, EventArgs e)
        {
            Function.Parameters.Add(
                new Parameter(EcoSpace)
                {
                    Name = "Parameter_" + Function.Parameters.Count.ToString()
                });
        }

        private void DelParamButton_Click(object sender, EventArgs e)
        {
            if (ParametersCMH.Element == null)
                return;

            (ParametersCMH.Element.AsObject as Parameter).AsIObject().Delete();
        } 

        #endregion

        private void OkButton_Click(object sender, EventArgs e)
        {
            result = true;
            Close();
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            result = false;
            Close();
        }

        private void FunctionEditForm_Load(object sender, EventArgs e)
        {
            undo.StartTransaction();
        }

        private void FunctionEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (result)
                undo.CommitTransaction();
            else
                undo.RollbackTransaction();
        }
    }
}
